//登录、注册模块的小仓库
import api from '@/api';
let state = {
    token: localStorage.getItem("TOKEN"),
    nickName: ''
};

let actions = {
    //注册
    async registerUser({ commit }, data) {
        let result = await api.reqUserRegister(data);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message));
        }
    },
    //登录
    async userLogin({ commit }, data) {
        let result = await api.reqUserLogin(data);
        if (result.code == 200) {
            commit('SET_TOKEN', result.data.token);
            localStorage.setItem('TOKEN', result.data.token);
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message));
        }
    },
    //退出登录
    async logout({ commit }) {
        commit('CLEAR');
        return 'ok';
    }
};

let mutations = {
    SET_TOKEN(state, token) {
        state.token = token;
    },
    SET_USERINFO(state, nickName) {
        state.nickName = nickName;
    },
    CLEAR(state) {
        state.token = '';
        state.nickName = '';
        localStorage.removeItem('TOKEN');
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
}